<template>
  <el-form ref="formRef" :model="formData" label-width="100px" size="large">
    <el-row v-for="(rowOption, index) in formConifg" :key="index">
      <el-col
        v-for="item in rowOption.row"
        :key="item.label"
        :span="item.span || 24 / rowOption.row.length"
      >
        <el-form-item
          :label="item.label"
          :prop="item.prop"
          :rules="item.rules"
          v-show="item.isShow ? item.isShow(formData) : true"
        >
          <component
            :is="item.component"
            v-model="formData[item.prop]"
            v-bind="item.attrs"
            style="width: 100%"
            @change="(val) => (item.change ? item.change(val, formData) : '')"
          ></component>
        </el-form-item>
      </el-col>
    </el-row>
    <div class="dialog-footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </div>
  </el-form>
</template>
<script setup>
import { ref, watch } from 'vue';
const props = defineProps({
  formData: {
    // 表单数据
    type: Object,
    default: () => {},
  },
  formConifg: {
    //表单配置项
    type: Array,
    default: () => [],
  },
});
const emit = defineEmits(['close', 'submit']);

const formRef = ref(null);
const formData = ref({});

watch(
  () => props.formData,
  (newVal) => {
    formData.value = newVal;
  },
  { immediate: true },
);

watch(
  () => props.formConifg,
  (newVal) => {
    newVal.forEach((rowOption) => {
      rowOption.row.forEach((item) => {
        //表单项中有配置默认值的，将其赋值给表单
        if (item.defaultValue) {
          formData.value[item.prop] = item.defaultValue;
        }
      });
    });
  },
  { immediate: true, deep: true },
);

const close = () => {
  emit('close');
};

const submitForm = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (valid) {
      emit('submit', formData.value);
      close();
    } else {
      return false;
    }
  });
};
</script>
<style lang="scss" scoped></style>
